//引入express
import express from "express";
import sha1 from "sha1";
import config from "../../config/index.js";

const router = express.Router()
//创建路由
router.get('/', (req, res) => {
    const { token } = config;
    //对req.query进行解构

    /**
     * {
        signature: 'f4dcb7f52c4acfeace4a5b30d2518a8989677ad5',
        echostr: '7245036684137313279',
        timestamp: '1711870420',
        nonce: '1815365949'
        }
        1）将token、timestamp、nonce三个参数进行字典序排序
  
        2）将三个参数字符串拼接成一个字符串进行sha1加密
  
        3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     */
    const { signature, echostr, timestamp, nonce } = req.query;
    // 1. 将token、timestamp、nonce三个参数进行字典序排序
    const arr = [token, timestamp, nonce].sort();
    // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
    const str = arr.join('');
    const sha = sha1(str);
    // 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
    if (sha === signature) {
        // 4. 将echostr原样返回
        res.send(echostr);
    } else {
        res.send('error');
    }
})

// 微信授权
router.get('/index', (req, res) => {
    res.send('ok')
})

// 导出路由
export default router;